package com.pickgliss.loader
{
	import com.pickgliss.ui.ComponentSetting;
	import com.pickgliss.ui.core.Component;
	import com.road.mapengine.bitmap.load.ResourceLoaderInfo;
	
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoaderDataFormat;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.utils.ByteArray;

	public class DomainResourceLoad extends BaseLoader
	{
		public  var tempData   : ResourceLoaderInfo;
		public static const B_SWF : String = ".bswf";
		private static var _loaderContext:LoaderContext;
		private static var _queue : SimpleQueueLoader ;
		private var _tempLoad : Loader;
		public function DomainResourceLoad(id:int, url:String)
		{
//			url = "aaaaaa" + url;
			LoaderHeaderList.addItem(url,this);
			super(id, url);
		}


		public static function get loaderContext():LoaderContext
		{
			return _loaderContext;
		}

		
		override protected function getLoadDataFormat():String
		{
			return URLLoaderDataFormat.BINARY;
		}
		
		public static function set loaderContext(value:LoaderContext):void
		{
			_loaderContext = value;
			if(_queue)_queue.dispose();
			_queue = null;
			if(value)
			{
				_queue = new SimpleQueueLoader(5);
			}			
		}

		private function loadFromBytesImp(data:ByteArray):void
		{
			if(!_loaderContext)
			{
				loaderContext = new LoaderContext(false,new ApplicationDomain(ApplicationDomain.currentDomain));
				_loaderContext.allowCodeImport = true;
			}
			if(_queue.allLoaderInUse || _tempLoad)
			{
				if(!_tempLoad)_queue.addQueue({fun:loadFromBytesImp,para:data});
				return;
			}
			_tempLoad = _queue.getLoader();
			_tempLoad.contentLoaderInfo.addEventListener(Event.COMPLETE,__onContentLoadComplete);
			_tempLoad.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, __ioErrorHandler);
			_tempLoad.loadBytes(data,_loaderContext);
		}
		private function __ioErrorHandler(evt : IOErrorEvent) : void
		{
			_tempLoad.contentLoaderInfo.removeEventListener(Event.COMPLETE,__onContentLoadComplete);
			_tempLoad.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, __ioErrorHandler);
			fireCompleteEvent();
			dispose();
		}
		override protected function __onIOError(event:IOErrorEvent):void
		{
			super.__onIOError(event);
			if(_isComplete && tempData)LoaderHeaderList.doesNotExist = tempData.url;
		}
		
		override protected function __onDataLoadComplete(event:Event):void
		{
			removeEvent();
			try{
				_loader.close();
			}
			catch(err :Error){}
			if(_loader.data.length == 0)return;
			var md5:String = ComponentSetting.getUrlMd5(_url);
			LoaderSavingManager.cacheFile(_url,_loader.data,false,md5);
			loadFromBytes(_loader.data);
		}
		
		override public function loadFromBytes(data:ByteArray):void
		{
			data.position = 0;
			var leng : int           = data.bytesAvailable;		
			var swfBytes : ByteArray = new ByteArray();	
			var embedData : Object   = new Object();
			try {
				while(data.position < leng)
				{
					var tag : int = data.readByte();
					switch(tag)
					{
						case 0x01:
							embedData['sizeType'] = data.readByte();
							break;
						case 0x02:
							embedData['standsPara'] = data.readUTF();
							break;
						case 0x03:
							embedData['walksPara'] = data.readUTF();
							break;
						case 0x04:
							embedData['noShadow'] = data.readBoolean();
							break;
						case 0x05:
							embedData['showNamePosY'] = data.readInt();
							break;
						case 0x06:
							embedData['curTotalFrameX'] = data.readByte();
							break;
						case 0x07:
							embedData['offsetY'] = data.readInt();
							break;
						case 0x08:
							embedData['attackPara'] = data.readUTF();
							break;
						case 0x10:
							var swfLeng : int = data.readInt();
							data.readBytes(swfBytes,0,swfLeng);
							swfBytes.position = 0;
							data.position = leng;
							break;
					}
				}
			} catch (e:Error) {
				this.onLoadError();
				trace("缓存错误  总共：", this._loader.bytesTotal,", 完成：", this._loader.bytesLoaded, ", url:",this._url);
				return;
			}
			
			
			LoaderHeaderList.deleteItem(tempData.url);
			LoaderHeaderList.avatarShowNamePos[tempData.url] = embedData;
			embedData = null;
			
			if(swfBytes.length > 0)loadFromBytesImp(swfBytes);
		}
		private var _currentTryTime:int = 0;
		override protected function onLoadError():void
		{
			if(_url == "http://10.10.3.50:8080/swf/avatar/fashion_hat_swimsuit03Down_mount/2_0.bswf")
			{
				trace("");
			}
			LoaderSavingManager.clearFiles(_url);
			if(_currentTryTime < TRY_LOAD_TIMES)
			{
				_currentTryTime++;
				_isLoading = false;
				startLoad(_url);
			}else
			{
				removeEvent();
				try{
					_loader.close();
				}
				catch(err :Error){}
				_isComplete = true;
				_isLoading = false;
				_isSuccess = false;
				dispatchEvent(new LoaderEvent(LoaderEvent.LOAD_ERROR,this));
				dispatchEvent(new LoaderEvent(LoaderEvent.COMPLETE,this));
			}
		}
		
		protected function __onContentLoadComplete(event:Event):void
		{
			_tempLoad.contentLoaderInfo.removeEventListener(Event.COMPLETE,__onContentLoadComplete);
			_tempLoad.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, __ioErrorHandler);
			fireCompleteEvent();
			dispose();
		}
		override public function dispose():void
		{
			if(!LoaderHeaderList.resourceDoesNotExist(tempData.url))LoaderHeaderList.deleteItem(tempData.url);
			if(_tempLoad)
			{
				_tempLoad.contentLoaderInfo.removeEventListener(Event.COMPLETE,__onContentLoadComplete);
				_tempLoad.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, __ioErrorHandler);
				_tempLoad.unloadAndStop(true);
				_queue.pushLoader(_tempLoad);
			}
			_tempLoad = null;
			super.dispose();
			
		}
		override public function get type():int
		{
			return BaseLoader.DOMAIN_RESOURCE_LOADER;
		}
	}
}